﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sqlite;
namespace SockLib
{
    public class logexception
    {
        //日志保存路径，不包括文件名  
        private static string filePath = System.AppDomain.CurrentDomain.BaseDirectory + "log\\SockLibException";
        //日志完整路径，包括文件名  
        //private static string file = filePath + "";  
        private static string logFileName = filePath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";

        /// <summary>  
        /// 创建文件夹和日志文件  
        /// </summary>  
        private static void CreateLogFile()
        {
            //文件不存在，则创建新文件  
            if (!Directory.Exists(filePath))
            {
                try
                {
                    //按照路径创建目录  
                    Directory.CreateDirectory(filePath);
                }
                catch (System.Exception e)
                {
                    throw new System.Exception(e + "创建目录失败！");
                }
            }
            if (!File.Exists(logFileName))
            {
                FileStream filestream = null;
                try
                {
                    filestream = File.Create(logFileName);
                    /*创建日志头部*/
                    filestream.Dispose();
                    filestream.Close();
                    CreateLogHead();
                }
                catch (System.Exception ex)
                {
                    throw new System.Exception(ex + "创建日志文件失败");
                }
            }
        }

        /// <summary>  
        /// 创建日志头部  
        /// </summary>  
        private static void CreateLogHead()
        {
            System.IO.StreamWriter sw = null;
            try
            {
                sw = new System.IO.StreamWriter(logFileName, true, System.Text.Encoding.UTF8);
                sw.WriteLine();
                sw.WriteLine("                     系统异常日志                   ");
                sw.WriteLine("【日志创建时间 " + DateTime.Now.ToString() + " 】   ");
                sw.WriteLine();
                sw.WriteLine();
            }
            catch 
            {
                //logexception.WriteLogToFile(ex);
            }
            finally
            {
                sw.Flush();
                sw.Dispose();
                sw.Close();
            }
        }

        /// <summary>  
        ///写入日志，  
        ///自动创建文件夹和文件，  
        ///日志文件创建到系统启动项根目录的Log文件夹下。  
        /// </summary>  
        /// <param name="logText">参数，日志内容</param>  
        /// <returns>日志写入成功返回true,失败返回false</returns>  
        public static void WriteLogToFile(string logText)
        {
            CreateLogFile();
            //true 如果日志文件存在则继续追加日志   
            System.IO.StreamWriter sw = null;
            try
            {
                sw = new System.IO.StreamWriter(logFileName, true, System.Text.Encoding.UTF8);
                sw.WriteLine(System.DateTime.Now.ToString() + " # " + logText);
            }
            catch (System.Exception ex)
            {
                //return false;  
                throw new System.Exception(ex + "写入日志失败，检查！");
            }
            finally
            {
                sw.Flush();
                sw.Dispose();
                sw.Close();
            }
        }

        /// <summary>
        /// 将异常写入
        /// </summary>
        /// <param name="log"></param>
        public static void WriteLogToFile(Exception log, bool IsBreak = false)
        {
            string logText = ExceptionString(log, IsBreak);
            //异常写入sqlite
           // WriteSqltie(log.Message, logText);
            //异常写入文件
            WriteLog(logText, IsBreak);

        }

        private static void WriteSqltie(string msg,string stack)
        {
            InsertLog.InsertSockLib(new object[] {SocketServer.ports , msg, stack });
        }

        private static  void  WriteLog(string logText, bool IsBreak = false)
        {
            CreateLogFile();
            //true 如果日志文件存在则继续追加日志   
            System.IO.StreamWriter sw = null;
            try
            {
                sw = new System.IO.StreamWriter(logFileName, true, System.Text.Encoding.UTF8);
                sw.WriteLine(System.DateTime.Now.ToString() + " # " + logText);
            }
            catch (System.Exception ex)
            {
                //return false;  
                throw new System.Exception(ex + "写入日志失败，检查！");
            }
            finally
            {
                sw.Flush();
                sw.Dispose();
                sw.Close();
            }
        }

        private static string ExceptionString(Exception e, bool IsBreak = false)
        {
            try
            {
                string exMsg = e.StackTrace;
                string[] exmsgs = exMsg.Split(Environment.NewLine.ToCharArray());
                string log = e.Message + Environment.NewLine;
                int PrintLen = 5;
                int PringIndex = 0;
                if (exmsgs.Length >= PrintLen * 2)
                    PringIndex = PrintLen * 2;
                else if (PringIndex < PrintLen * 2)
                    PringIndex = exmsgs.Length;
                else
                    PringIndex = PrintLen * 2;
                string log4stack = "";
                for (int i = 0; i < PringIndex; i++)
                {
                    if (exmsgs[i] != "")
                        log4stack += exmsgs[i] + Environment.NewLine;
                }
                if (IsBreak)
                    log4stack += "**********************************" + Environment.NewLine;
                else
                    log4stack += "----------------------------------" + Environment.NewLine;
                log += log4stack;
                return log;
            }
            catch (Exception)
            {
                return DateTime.Now.ToString() + " | " + "异常捕获失败";
            }

        }

    }
}
